package com.wt.chat.controller;

import com.wt.chat.cache.RedisCache;
import com.wt.chat.context.ContextHolder;
import com.wt.chat.entity.Dialog;
import com.wt.chat.entity.Message;
import com.wt.chat.file.FileStoreSystem;
import com.wt.chat.response.ResponseResult;
import com.wt.chat.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description
 * @author: wangtao
 * @date:9:38 2019/11/12
 * @email:taow02@jumei.com
 */
@Controller
@RequestMapping("/message")
public class MessageController {

	@Autowired
	private MessageService messageService;

	@Autowired
	private RedisCache redisCache;

	@Autowired
	private FileStoreSystem fileStoreSystem;

	@RequestMapping("/polling")
	public ResponseResult polling() {
		Integer kefuId = ContextHolder.currentKefuId();
		Map<String, List<Message>> map = messageService.pollingByKefuId(kefuId);
		return new ResponseResult().code(0).body(map);
	}

	@RequestMapping("/init/{dialogId}")
	public ResponseResult init(@PathVariable("dialogId") Integer dialogId) {
		List<Message> msgs = messageService.findByDialogId(dialogId);
		return new ResponseResult().code(0).body(msgs);
	}

	@RequestMapping("/send/{userId}")
	public ResponseResult send(@PathVariable("userId") Integer userId, @RequestBody Message message) {
		message.setStatus(1);
		message.setCreateTime(new Date());
		messageService.sendMessage(message);
		messageService.notify(userId, message);
		return new ResponseResult().code(0);
	}

	@RequestMapping("/sendFile/{userId}")
	public ResponseResult sendFile(@RequestParam(value = "file") MultipartFile file, @PathVariable("userId") Integer userId, Message message)
			throws Exception {
		message.setStatus(1);
		message.setCreateTime(new Date());
		message.setType(Message.MsgType.FILE.getValue());
		message.setSender(Message.SenderType.KEFU.getValue());
		message.setContent(fileStoreSystem.save(file.getInputStream(), file.getOriginalFilename()));
		messageService.sendMessage(message);
		messageService.notify(userId, message);
		return new ResponseResult().code(0).body(message);
	}

	@RequestMapping("/file/get")
	public void getFile(@RequestParam("path") String path, HttpServletResponse response) throws Exception {
		FileInputStream fis = new FileInputStream(path);
		OutputStream outputStream = response.getOutputStream();
		byte[] b = new byte[10240];
		int len = 0;
		while ((len = fis.read(b)) != -1) {
			outputStream.write(b, 0, len);
		}
		outputStream.flush();
		outputStream.close();
		fis.close();
	}

}
